package net.sxnic.ugr.role.action;

import net.sxnic.ugr.menu.Menu;
import net.sxnic.ugr.role.Role;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
@SuppressWarnings("serial")
public class Save extends RoleAction {
	
	private static Logger logger = LoggerFactory.getLogger(Save.class);

	public void prepare() throws Exception {
		if(StringUtils.isNotBlank(id))
			role = authorizationManager.getRoleById(id);
	}

	public String execute() throws Exception {

		try {
			checkRoles(Role.SYSTEM_ADMIN);

//			//设定选择的菜单列表
//			role.getMenus().clear();
//			Menu m = null;
//			for (String mid : menus) {
//				m = menuManager.get(mid.trim());
//				logger.debug("menu id :" + m.getId() + " , role id :"
//						+ role.getId());
//
//				role.getMenus().add(m);
//
//			}

			//设定所选择的权限列表
//			role.getPermissions().clear();
//			Permission p = null;
//			for (String pid : perms) {
//				p = permissionManager.get(pid);
//				logger.debug("permission id :" + p.getId() + " , role id :"
//						+ role.getId());
//				role.getPermissions().add(p);
//
//			}
			
			// 角色
			if (StringUtils.isBlank(menu)) {
				role.getMenus().clear();
				 
			} else {
				 
				String[] menus = StringUtils.split(menu, ",");
				role.getMenus().clear();
				authorizationManager.updateRole(role);
				Menu m = null;
				for (String rr : menus) {
					m = authorizationManager.getMenu (rr.trim());
					logger.debug("menu id :" + m.getId() + " , role id :"
							+ role.getId());

					role.getMenus().add(m);
					 
				}
				//user.setRoleCodes(StringUtils.removeEnd(tempCodes, ","));
			} 
			
			if(StringUtils.isBlank(role.getId()))
				roleManager.save(role);
			else
				roleManager.update(role);

			// 保存成功信息并转向
			msg = "saveSuccess";

		} catch (Exception e) {
			e.printStackTrace();
		}

		return SUCCESS;
	}

}
